<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }" class="box-card">
      <template #header>
        <div>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="addBtn"
            >添加</el-button
          >
        </div>
      </template>
      <el-table border :data="trademarkListPage" stripe style="margin: 20px 0">
        <el-table-column type="index" width="50" label="序号" align="center" />
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <el-image
              :src="row.logoUrl"
              fit="fill"
              :lazy="true"
              style="width: 66px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-edit"
              @click="updateBtn(row)"
              >修改</el-button
            >
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @onConfirm="deleteAttr(row.id)"
            >
              <el-button
                style="margin-left: 10px;"
                slot="reference"
                size="mini"
                icon="el-icon-delete"
                type="danger"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-sizes="[3, 5, 8, 10]"
        :page-size.sync="pageSize"
        :page-count="pageCount"
        background
        layout=" sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </el-card>
    <!-- 添加或修改的弹窗 -->
    <el-dialog
      :title="trademarkForm.id ? '修改品牌' : '新增品牌'"
      :visible.sync="isShowDialog"
      width="50%"
    >
      <el-form
        :model="trademarkForm"
        ref="trademarkForm"
        :rules="rules"
        label-width="100px"
        :inline="false"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="trademarkForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkForm.logoUrl"
              :src="trademarkForm.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="resetForm('trademarkForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('trademarkForm')"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqGetTrademarkListPage,
  reqAddTrademark,
  reqUpdataTradmark,
  reqDeleteTradmark,
} from "@/api/product/trademark";
export default {
  name: "Trademark",
  data() {
    return {
      currentPage: 1, //当前页码
      pageSize: 5, //当前连续页
      pageCount: 0, //总页数
      trademarkListPage: [], //列表数据
      isShowDialog: false, //控制弹窗是否关闭
      trademarkForm: {
        //收集表单的初始绑定数据
        id: null,
        tmName: "",
        logoUrl: "",
      },
      rules: {
        //表单校验规则
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
        ],
        logoUrl: [
          { required: true, message: "请上传品牌LOG", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //请求列表数据
    async getTrademarkListPage() {
      try {
        const result = await reqGetTrademarkListPage(
          this.currentPage,
          this.pageSize
        );
        console.log(result);
        this.pageCount = result.pages;
        this.trademarkListPage = result.records;
      } catch (error) {
        this.$message({
          message: error.message,
          type: "error",
        });
      }
    },
    handleAvatarSuccess(res, file) {
      this.trademarkForm.logoUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt8M = file.size / 1024 / 1024 < 8;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt8M) {
        this.$message.error("上传头像图片大小不能超过 8MB!");
      }
      return isJPG && isLt8M;
    },
    //点击添加按钮事件回调
    addBtn() {
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.$refs["trademarkForm"].resetFields();
      });
      setTimeout(()=>{
        this.trademarkForm = {
          //重置表单数据
          id: null,
          tmName: "",
          logoUrl: "",
        };
      },0)
    },
    //点击修改按钮事件回调函数
    updateBtn(row) {
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.$refs["trademarkForm"].resetFields();
      });
      setTimeout(()=>{
        this.trademarkForm = row;
      },0)
    },
    //点击提交按钮
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            if (this.trademarkForm.id) {
              await reqUpdataTradmark(this.trademarkForm);
              this.$message.success("更新列表成功！");
              this.getTrademarkListPage();
            } else {
              await reqAddTrademark(this.trademarkForm);
              this.$message.success("添加列表成功！");
              this.getTrademarkListPage();
            }
          } catch (error) {
            this.$message.error(error.message);
          }
        } else {
          this.$message({
            message: "校验出现错误，请检查！",
            type: "error",
          });
          return false;
        }
        this.isShowDialog = false;
      });
    },
    //点击取消按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.isShowDialog = false;
    },
    //点击删除按钮事件回调
    async deleteAttr(id) {
      try {
        await reqDeleteTradmark(id);
        this.$message({
          message: "恭喜你，删除成功！",
          type: "success",
        });
        this.getTrademarkListPage();
      } catch (error) {
        this.$message({
          message: error.message,
          type: "error",
        });
      }
    },
  },
  mounted() {
    this.getTrademarkListPage();
  },
  watch: {
    //监听页码改变，重新发送请求
    currentPage() {
      this.getTrademarkListPage();
    },
    pageSize() {
      this.getTrademarkListPage();
    },
  },
};
</script>

<style lang="scss" scoped>
.box-card {
  margin: 30px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
